<template>
    <div id="gojs_page">
        <!-- 顶部图标 -->
        <div class="gojs_page_header">
            <div>
                <i class="el-icon-view" title="查看JSON数据" @click="save"></i>
                <i
                    class="el-icon-document-add"
                    title="新建"
                    @click="drawingNew"
                ></i>
                <i
                    class="el-icon-caret-top"
                    title="上移"
                    @click="move('up')"
                ></i>
                <i
                    class="el-icon-caret-bottom"
                    title="下移"
                    @click="move('down')"
                ></i>
                <i
                    class="el-icon-caret-left"
                    title="左移"
                    @click="move('left')"
                ></i>
                <i
                    class="el-icon-caret-right"
                    title="右移"
                    @click="move('right')"
                ></i>
                <i
                    class="el-icon-refresh-right"
                    title="旋转+45°"
                    @click="changeAngle('+')"
                ></i>
                <i
                    class="el-icon-refresh-left"
                    title="旋转-45°"
                    @click="changeAngle('-')"
                ></i>
                <i
                    class="el-icon-full-screen"
                    title="满屏显示"
                    @click="showAll"
                ></i>
                <i
                    class="el-icon-zoom-in"
                    title="放大"
                    @click="zoomChange('+')"
                ></i>
                <i
                    class="el-icon-zoom-out"
                    title="缩小"
                    @click="zoomChange('-')"
                ></i>
                <i
                    class="el-icon-refresh"
                    title="还原大小"
                    @click="zoomChange(1)"
                ></i>
                <i
                    class="el-icon-back"
                    title="后退"
                    @click="redoAndUndo('un')"
                ></i>
                <i
                    class="el-icon-right"
                    title="前进"
                    @click="redoAndUndo('re')"
                ></i>
            </div>
            <div>
                <el-button @click="onSeeFail">字段说明</el-button>
            </div>
        </div>
        <div class="gojs_page_content">
            <!-- 左侧调色板 -->
            <div class="gojs_page_left">
                <div id="myPaletteDiv">
                            <canvas
                                tabindex="0"
                                width="100"
                                height="750"
                                style="
                                    position: absolute;
                                    top: 0px;
                                    left: 0px;
                                    z-index: 2;
                                    user-select: none;
                                    width: 100px;
                                    height: 750px;
                                    cursor: auto;
                                "
                                >如果浏览器不支持Canvas
                                HTML元素，则显示此文本。</canvas
                            >
                            <div
                                style="
                                    position: absolute;
                                    overflow: auto;
                                    width: 100px;
                                    height: 750px;
                                    z-index: 1;
                                "
                            >
                                <div
                                    style="
                                        position: absolute;
                                        width: 1px;
                                        height: 1px;
                                    "
                                ></div>
                            </div>
                        </div>
            </div>
            <!-- 中间画图区 -->
            <div class="middle-box">
                <div id="myDiagramDiv" class="gojs_page_middle">
                    <canvas
                        tabindex="0"
                        width="804"
                        height="750"
                        style="
                            position: absolute;
                            top: 0px;
                            left: 0px;
                            z-index: 2;
                            user-select: none;
                            width: 804px;
                            height: 750px;
                            cursor: auto;
                        "
                        >如果浏览器不支持Canvas HTML元素，则显示此文本。</canvas
                    >
                    <div
                        style="
                            position: absolute;
                            overflow: auto;
                            width: 804px;
                            height: 750px;
                            z-index: 1;
                        "
                    >
                        <div
                            style="position: absolute; width: 1px; height: 1px"
                        ></div>
                    </div>
                </div>
                <!-- 缩略图 -->
                <div id="myOverviewDiv"></div>
            </div>

            <!-- 右侧属性兰 -->
            <Panel
                ref="panel"
                :myDiagram="myDiagram"
                :formData="formData"
                :customFormList="customFormList"
                :nodeWidth="nodeWidth"
                :nodeHeight="nodeHeight"
                @change-from-child="publicChange"
                @update-view="updateDiagramFromData"
            >
            </Panel>
        </div>
        <!-- 数据弹窗 -->
        <el-dialog title="提示" :visible.sync="dialogVisible" width="450">
            <textarea
                v-model="jsonData"
                style="width: 100%; height: 300px"
            ></textarea>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogVisible = false"
                    >确 定</el-button
                >
            </span>
        </el-dialog>
        <!-- 字段说明 -->
        <el-dialog
            title="字段说明"
            custom-class="gojs-dialog"
            :visible.sync="dialogVisible1"
            width="450"
        >
            <el-table
                :header-cell-style="tableHeaderColor"
                height="500"
                :data="tableData"
            >
                <el-table-column
                    prop="key"
                    label="字段"
                    align="center"
                    width="120"
                    show-overflow-tooltip
                >
                </el-table-column>
                <el-table-column
                    prop="val"
                    label="值"
                    align="center"
                    show-overflow-tooltip
                >
                    <template slot-scope="scope">
                        <span>{{ scope.row.val }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="des" label="说明" show-overflow-tooltip>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script>
import {
    getUrlKey,
    setDataByCustomApi,
    getDataByCustomApi,
} from "@/tools/index.js";
import Panel from "./panel/index";
// import { getDeviceListByType1 } from "@/api/publicApi.js";
import "../../gojs/go.min.js"; //引入gojs
import "../EnlargeFile/Figures"; //引入gojs预定义图形
import gojsData from "./info.json"; //初始图形数据
import Mixin from "./mixin";
export default {
    data() {
        return {
            tableData: [],
            dialogVisible1: false,
            nodeWidth: 0,
            nodeHeight: 0,
            formData: {},
            customFormList: [
                {
                    name: "",
                    value: "",
                },
            ],
            renderPower: true, //是否渲染供电图例
            dialogVisible: false,
            jsonData: "", //画布中图形所产生的数据
            myDiagram: null, //中间画布区
            myPalette: null, //调色板
            customApiObj: {},
            mapData: {},
            isUpdate: false,
        };
    },
    mixins: [Mixin],
    components: {
        Panel,
    },
    mounted() {
        this.init();
    },
    methods: {
        //表头样式
        tableHeaderColor({ row, column, rowIndex, columnIndex }) {
            if (rowIndex === 0) {
                return "font:14px '微软雅黑';color:#333;font-weight: 900;background-color: #F2F2F2";
            }
        },
        onSeeFail() {
            let obj = {
                businessId: "业务id（自定义）", //业务id
                category: "图例标识",
                size: '图形宽高（"width height"，例："100 50"）',
                textAlign: "文本对齐方式（left,center,right）",
                fontSize: "字体大小(数字)",
                fontWeight: "是否加粗（true/false）",
                underline: "是否添加下划线（true/false）",
                background:
                    "背景颜色（颜色单词/十六进制/rgba，例：red /#fff /rgba(255,0,0,0.5)）",
                text: "文本内容",
                nodeName: "节点描述",
                stroke:
                    "图形、文本颜色（颜色单词/十六进制/rgb，例：red /#fff /rgb(255,0,0)）",
                angle: "旋转角度（数字）",
                customData: "自定义信息（例：[{name:'name',value:'张三'}]）",
                loc: '图形中心坐标（"x y"，例："100 200"）',
                lightState: "信号灯状态",
                textVisible: "图形下的文本是否显示",
                key: "图形自动生成的id",
                flip: "铁鞋方向（None（向右）、FlipHorizontal（向左））",
                trackType:
                    "线类型（股道:commonLine;无岔:noFault;岔前:forkFront;反位:contraposition;定位:location;区间:section;辅助线:guide;专用线:specialLine）",
            };
            this.dialogVisible1 = true;
            let arr = [];
            let tempObj = JSON.parse(JSON.stringify(this.formData));
            delete tempObj.__gohashid;
            delete tempObj.key;
            delete tempObj.textVisible;
            if (tempObj.category === "circularLight") {
                obj.lightState = "信号灯状态(1,2,3,4,5)";
            }
            if (tempObj.category === "doubleLight") {
                obj.lightState = "信号灯状态(1,2,3)";
            }
            for (let key in tempObj) {
                let o = {
                    key: key,
                    val: tempObj[key],
                    des: obj[key],
                };
                arr.push(o);
            }
            this.tableData = arr;
            console.log(this.formData);
        },
        /** 新建图形 */
        drawingNew() {
            this.isUpdate = false;
            let newdata = {
                class: "go.GraphLinksModel",
                linkFromPortIdProperty: "fromPort",
                linkToPortIdProperty: "toPort",
                nodeDataArray: [],
                linkDataArray: [],
            };
            this.myDiagram.model = go.Model.fromJson(newdata);
        },
        /** 这是默认动画的重新实现，只是它从下而不是向上淡入。 */
        animateFadeDown(e) {
            let diagram = e.diagram;
            let animation = new go.Animation();
            animation.isViewportUnconstrained = true; // 所以图表定位规则让动画从屏幕上开始
            animation.easing = go.Animation.EaseOutExpo;
            animation.duration = 900;
            // 淡入，换句话说，从上面淡入
            animation.add(
                diagram,
                "position",
                diagram.position.copy().offset(0, 200),
                diagram.position
            );
            animation.add(diagram, "opacity", 0, 1);
            animation.start();
        },
        /** 前进、后退 */
        redoAndUndo(type) {
            type == "re"
                ? this.myDiagram.undoManager.redo()
                : this.myDiagram.undoManager.undo();
        },
        /** 满屏显示 */
        showAll() {
            this.myDiagram.zoomToFit();
        },
        /** 缩放 */
        zoomChange(val) {
            if (val === "-") {
                this.myDiagram.scale -= 0.1;
            } else if (val === "+") {
                this.myDiagram.scale += 0.1;
            } else {
                this.myDiagram.scale = 1;
            }
            let nodeOrLinkList = this.myDiagram.selection; //获取选中的节点或线
            if (nodeOrLinkList.Ue) {
                let key = nodeOrLinkList.Ue.key.data.key;
                this.myDiagram.scrollToRect(
                    this.myDiagram.findNodeForKey(key).actualBounds
                );
            }
        },
        /** 以JSON格式显示图表的模型 */
        save() {
            this.jsonData = this.myDiagram.model.toJson();
            this.dialogVisible = true;
        },
        /** 将数据渲染成图形 */
        load(val) {
            this.myDiagram.model = go.Model.fromJson(
                val ? this.mapData : gojsData
            );
            this.myDiagram.zoomToFit();
        },
        /** 上下左右移动 */
        move(dir) {
            let nodeOrLinkList = this.myDiagram.selection; //获取选中的节点或线
            let _this = this;
            nodeOrLinkList.each(function (nodeOrLink) {
                let nodeData = nodeOrLink.data;
                let x = Number(nodeData.loc.split(" ")[0]),
                    y = Number(nodeData.loc.split(" ")[1]);
                switch (dir) {
                    case "left":
                        x -= 1;
                        break;
                    case "up":
                        y -= 1;
                        break;
                    case "right":
                        x += 1;
                        break;
                    case "down":
                        y += 1;
                        break;
                    default:
                        break;
                }
                //所有模型更改都应该发生在事务中
                _this.myDiagram.model.commit(function (m) {
                    m.set(nodeData, "loc", x + " " + y);
                }, "flash");
            });
        },
        /** 旋转 */
        changeAngle(type) {
            let nodeOrLinkList = this.myDiagram.selection; //用例获取选中的节点或线
            let _this = this;
            nodeOrLinkList.each(function (nodeOrLink) {
                let nodeData = nodeOrLink.data;
                let a = nodeData.angle;
                switch (type) {
                    case "-":
                        a -= 45;
                        break;
                    case "+":
                        a += 45;
                        break;
                    default:
                        break;
                }
                //所有模型更改都应该发生在事务中
                _this.myDiagram.model.commit(function (m) {
                    m.set(nodeData, "angle", a);
                }, "flash");
            });
        },
        /**改变颜色 */
        colorChange(val) {
            this.publicChange("stroke", val || "#fff");
        },
        /**改变当前选中节点属性的公用方法 */
        publicChange(type, val) {
            let nodeOrLinkList = this.myDiagram.selection; //用例获取选中的节点或线
            let _this = this;
            nodeOrLinkList.each(function (nodeOrLink) {
                let nodeData = nodeOrLink.data;
                //所有模型更改都应该发生在事务中
                _this.myDiagram.model.commit(function (m) {
                    m.set(nodeData, type, val);
                }, "flash");
            });
        },
        /**改变长度 */
        widthChange(val) {
            this.publicChange("size", val);
        },
        /**改变角度 */
        angleChange(val) {
            this.publicChange("angle", val);
        },
        /**更新视图 */
        updateDiagramFromData() {
            this.myDiagram.startTransaction();
            this.myDiagram.updateAllRelationshipsFromData();
            this.myDiagram.updateAllTargetBindings();
            this.myDiagram.commitTransaction("updated");
        },
        getUrlData() {
            this.customApiObj = {};
            let code = getUrlKey("url", window.location.href);
            if (code) {
                console.log(decodeURIComponent(window.atob(code)));
                this.customApiObj.url = decodeURIComponent(window.atob(code));
            }
        },
    },
    created() {
        this.getUrlData();
    },
    beforeDestroy() {},
};
</script>
<style lang="less">
canvas {
    border: 0px;
    outline: none;
}
.gojs_page_left {
    .el-tabs {
        color: #fff;
        height: 100%;
    }
    .el-tabs__header {
        margin: 0 0 10px;
    }
    .el-tabs__item {
        color: #fff;
        font-size: 16px;
    }
    .el-tabs__content {
        height: calc(100% - 50px);
    }
    .el-tab-pane {
        height: 100%;
    }
}
.gojs-dialog {
    border-radius: 5px;
    .el-dialog__header {
        padding-bottom: 10px;
        padding-top: 10px;
        background-color: #ededed;
        border-radius: 5px 5px 0 0;

        span {
            font-size: 16px;
        }
        button {
            top: 15px;
        }
    }
    .el-dialog__body {
        padding: 20px 0px;
    }
    .el-table__body tr.current-row > td {
        background-color: rgba(64, 158, 255, 1);
        color: #fff;
    }
    .el-table__row {
        cursor: pointer;
    }
}
</style>
<style lang="less" scoped>
@import "./index.less";
</style>